package org.durcframework.rms.service;

import java.util.List;

import org.durcframework.core.expression.QBC;
import org.durcframework.core.service.CrudService;
import org.durcframework.rms.constant.RoleType;
import org.durcframework.rms.dao.AddGroupUserPojo;
import org.durcframework.rms.dao.RGroupUserDao;
import org.durcframework.rms.entity.RGroup;
import org.durcframework.rms.entity.RGroupUser;
import org.durcframework.rms.entity.UserRoleParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RGroupUserService extends CrudService<RGroupUser, RGroupUserDao> {

	@Autowired
	private RGroupService groupService;
	@Autowired
	private RUserRoleService userRoleService;
	@Autowired
	private RGroupRoleService groupRoleService;
	
	/**
	 * 添加用户组成员
	 * 1. 添加用户组成员表数据
	 * 2. 添加用户组成员角色
	 * @param addGroupUserPojo
	 */
	public void addGroupUser(AddGroupUserPojo addGroupUserPojo) {
		
		RGroup group = groupService.get(addGroupUserPojo.getGroupId());
		if(group == null) {
			return;
		}
		
		// 1
		this.getDao().addGroupUser(addGroupUserPojo);
		// 2
		List<Integer> roleIds = groupRoleService.getRoleIdsByGroupId(addGroupUserPojo.getGroupId());
		List<String> usernames = addGroupUserPojo.getUsernames();
		
		UserRoleParam userRoleParam = null;
		for (String username : usernames) {
			userRoleParam = new UserRoleParam();
			userRoleParam.setRoleIds(roleIds);
			userRoleParam.setRoleType(RoleType.GROUP);
			userRoleParam.setUsername(username);
			userRoleService.setUserRole(userRoleParam);
		}
		
	}
	
	/**
	 * 根据groupId获取用户组数据
	 * @param groupId
	 * @return
	 */
	public List<RGroupUser> getGroupUserByGroupId(int groupId) {
		QBC<RGroupUser> qbc = QBC.create(this.getDao());
		qbc.eq("group_id", groupId);
		return qbc.listAll();
	}
	
	/**
	 * 删除用户组成员
	 * 1. 删除用户组成员表数据
	 * 2. 删除成员对应的角色
	 * 3. 删除权限数据
	 */
	@Override
	public void del(RGroupUser entity) {
		this.getDao().delGroupUser(entity);
	}
	
}